﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "batchreplacer.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QThread>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    // 创建替换器并移到子线程（避免UI卡顿）
    m_replacer = new BatchReplacer();
    m_workerThread = new QThread(this);
    m_replacer->moveToThread(m_workerThread);
    
    // 连接信号槽
    connect(m_workerThread, &QThread::finished, m_replacer, &QObject::deleteLater);
    connect(this, &MainWindow::startReplaceSignal, m_replacer, &BatchReplacer::startReplace);
    connect(m_replacer, &BatchReplacer::progressUpdated, this, &MainWindow::updateProgress);
    connect(m_replacer, &BatchReplacer::replaceFinished, this, &MainWindow::showResult);
    connect(m_replacer, &BatchReplacer::logMessage, this, &MainWindow::addLogMessage);
    
    m_workerThread->start();
}

MainWindow::~MainWindow()
{
    m_workerThread->quit();
    m_workerThread->wait();
    delete ui;
}

// 选择根目录
void MainWindow::on_selectDirBtn_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(this, "选择根目录", QDir::homePath());
    if (!dir.isEmpty()) {
        ui->dirPathEdit->setText(dir);
    }
}

// 开始替换
void MainWindow::on_startReplaceBtn_clicked()
{
    // 验证输入
    QString rootDir = ui->dirPathEdit->text();
    QString rulesText = ui->replaceRulesEdit->toPlainText();
    
    if (rootDir.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请选择根目录");
        return;
    }
    
    if (rulesText.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请至少添加一组替换规则");
        return;
    }
    
    // 解析替换规则（格式：旧字符串=新字符串，每行一组）
    QMap<QString, QString> replaceRules;
    QStringList lines = rulesText.split('\n', Qt::SkipEmptyParts);
    for (const QString &line : lines) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.isEmpty()) continue;
        
        int eqIndex = trimmedLine.indexOf('=');
        if (eqIndex <= 0) { // 确保有有效的分隔符
            QMessageBox::warning(this, "规则错误", QString("无效的规则格式：%1\n正确格式：旧字符串=新字符串").arg(line));
            return;
        }
        
        QString oldStr = trimmedLine.left(eqIndex);
        QString newStr = trimmedLine.mid(eqIndex + 1);
        replaceRules[oldStr] = newStr; // 存储到映射表
    }
    
    // 获取文件扩展名和排除目录
    QStringList fileExtensions = ui->fileExtEdit->text().split(',', Qt::SkipEmptyParts);
    for (int i = 0; i < fileExtensions.size(); ++i) {
        fileExtensions[i] = fileExtensions[i].trimmed().toLower();
    }
    
    QStringList excludeDirs = ui->excludeDirEdit->text().split(',', Qt::SkipEmptyParts);
    
    // 清空日志，设置参数并开始替换
    ui->logTextEdit->clear();
    m_replacer->setParameters(rootDir, replaceRules, fileExtensions, excludeDirs);
    emit startReplaceSignal();
}

// 更新进度条
void MainWindow::updateProgress(int current, int total)
{
    ui->progressBar->setMaximum(total);
    ui->progressBar->setValue(current);
}

// 显示替换结果
void MainWindow::showResult(int filesProcessed, int filesModified)
{
    QMessageBox::information(this, "替换完成", 
        QString("处理完成！\n共处理 %1 个文件\n成功替换 %2 个文件").arg(filesProcessed).arg(filesModified));
}

// 添加日志信息
void MainWindow::addLogMessage(const QString &message)
{
    ui->logTextEdit->append(message);
    // 自动滚动到最新日志
    QTextCursor cursor = ui->logTextEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->logTextEdit->setTextCursor(cursor);
}
    
